const Router = require('koa-Router')
let router = new Router()
//安防管理
const useprotectRouter = require('./protect/index')
//设备运维
const useEuipmentRouter = require('./equ/index')


router.use('/protect', useprotectRouter)
router.use('/euipment', useEuipmentRouter)

//登录后台
const path = require('path')
const fs = require('fs')
const jwt = require('jsonwebtoken')
//引入
const userdata = require('../database/user.json')
const roledata = require('../database/role.json')
const authdata = require('../database/auth.json')
//读取文件
const userdatapath = path.join(__dirname, '../' + 'database' + 'user.json')
const roledatapath = path.join(__dirname, '../' + 'database' + 'role.json')
const authdatapath = path.join(__dirname, '../' + 'database' + 'auth.json')


//登录接口
router.post('/api/login', ctx => {
    const { username, password } = ctx.request.body;
    let flag = userdata.some(item => item.username == username && item.password == password)
    let user = userdata.find(item => item.username == username && item.password == password)
    let role = roledata.find(item => item.id == user.roleid)
    if (flag) {
        let token = jwt.sign({
            data: username
        }, 'secret', { expiresIn: 60 * 60 });
        ctx.body = {
            code: 200,
            msg: "登录成功",
            token,
            user,
            rolename: role.rolename,
            auths: authdata[role.auths]
        }
    }
    else {
        ctx.body = {
            code: 400,
            msg: '登录失败'
        }
    }
})

module.exports = router